package com.geotmt.billingcenter.modules.schedule;

import com.alibaba.druid.util.StringUtils;
import com.geotmt.billingcenter.common.entry.ConsumeStatisEntry;
import com.geotmt.billingcenter.common.entry.CostStatisEntry;
import com.geotmt.billingcenter.common.utils.GeoDateUtils;
import com.geotmt.billingcenter.common.utils.IpUtils;
import com.geotmt.billingcenter.modules.consume.service.ConsumeService;
import com.geotmt.billingcenter.modules.cost.service.CostService;
import com.geotmt.billingcenter.modules.hive.service.ConsumeHiveService;
import com.geotmt.billingcenter.modules.hive.service.CostHiveService;
import com.geotmt.billingcenter.modules.statis.service.ConsumeStatisService;
import com.geotmt.billingcenter.modules.statis.service.CostStatisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * @Description 定时调度类（临时）
 * @Author      yanghanwei
 * @Mail        yanghanwei@geotmt.com
 * @Date        2019/4/11 15:09
 * @Version     v1
 **/
@Component
public class BcSchedule {

    private static final Logger logger = LoggerFactory.getLogger(BcSchedule.class);

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ConsumeHiveService consumeHiveService;

    @Resource
    private CostHiveService costHiveService;

    @Resource
    private ConsumeStatisService consumeStatisService;

    @Resource
    private CostStatisService costStatisService;

    @Resource
    private ConsumeService consumeService;

    @Resource
    private CostService costService;

    @Value("${statis.schedule.open}")
    private Boolean statisOpen;

    @Value("${master.ip}")
    private String masterIp;

    /**
     * 调度从hive -> mysql 消耗量统计
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void hiveToMysqlForConsume() {
        logger.info("进入consume定时器");
        if(!statisOpen || !judgeIpIsSame()){
            return;
        }
        try {
            Date preDay = GeoDateUtils.getPreDay(new Date(), -1);
            String day = GeoDateUtils.dateStr(preDay, GeoDateUtils.DATE_FORMAT2);
            // 1 为避免重复先调用一下删除历史接口
            consumeStatisService.deleteConsumeStatis(day);
            List<ConsumeStatisEntry> consumeStatisList = consumeHiveService.listConsume(day);
            if(null != consumeStatisList && !consumeStatisList.isEmpty()){
                // 2 批量插入mysql
                consumeStatisService.batchInsertStatis(consumeStatisList);
                // 3 更新维度信息
                String dateStr = GeoDateUtils.getDateStr(preDay, GeoDateUtils.DATE_FORMAT2);
                consumeStatisService.updateConsumeStatis(dateStr,dateStr,null);
                // 4 计算消耗并更新到统计表中
                consumeStatisService.getMoneyAndUpdateConsumeMoney(consumeService ,consumeStatisList, preDay);
            }
        } catch (Exception e) {
            logger.error("调度从hive -> mysql 消耗量统计Exception:",e);
        }
    }


    /**
     * 调度从hive -> mysql 成本量统计
     */
    @Scheduled(cron = "0 5 3 * * ?")
    public void hiveToMysqlForCost() {
        if(!statisOpen || !judgeIpIsSame()){
            return;
        }
        try {
            Date preDay = preDay = GeoDateUtils.getPreDay(new Date(), -1);
            String day = GeoDateUtils.dateStr(preDay, GeoDateUtils.DATE_FORMAT2);
            // 1 为避免重复先调用一下删除历史接口
            costStatisService.deleteCostStatis(day);
            List<CostStatisEntry> costStatisList = costHiveService.listCost(day);
            if(null != costStatisList && !costStatisList.isEmpty()){
                // 2 批量插入mysql
                costStatisService.batchInsertStatis(costStatisList);
                // 3 更新维度信息
                String dateStr = GeoDateUtils.getDateStr(preDay, GeoDateUtils.DATE_FORMAT2);
                costStatisService.updateCostStatis(dateStr,dateStr,null);
                // 4 计算成本并更新到统计表中
                costStatisService.getBatchMoneyAndUpdateConsumeMoney(costService, costStatisList, preDay);
            }
        } catch (Exception e) {
            logger.error("调度从hive -> mysql 成本统计Exception:",e);
        }
    }

    /**
     * 避免schedule 重复执行
     * @param flag
     * @param preDay
     * @return
     */
    private boolean judgeIfRunningSchedule(String flag, String preDay){
        boolean result = false;
        String dayStr = redisTemplate.opsForValue().get(flag) + "";
        if(!StringUtils.isEmpty(dayStr) && dayStr.equals(preDay)){
            result = true;
        } else {
            redisTemplate.opsForValue().set(flag, preDay);
        }
        return result;
    }

    /**
     * 判断当前server是否是主节点
     * @return
     */
    private boolean judgeIpIsSame(){
        return IpUtils.isSame(masterIp);
    }

}
